package indi.zjh.dp.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Iterator;

import indi.zjh.dp.vc.FileObject;

public class FileUtil {

	/**
	 * 拷贝文件
	 * @param file
	 * @param toFile
	 * @throws Exception
	 */
	public static void copy(File file, File toFile) throws Exception 
	{  
        byte[] b = new byte[1024];  
        int a;  
        FileInputStream fis;  
        FileOutputStream fos;  
        if (file.isDirectory()) 
        {  
            String filepath = file.getAbsolutePath();  
            filepath=filepath.replaceAll("\\\\", "/");  
            String toFilepath = toFile.getAbsolutePath();  
            toFilepath=toFilepath.replaceAll("\\\\", "/");  
            int lastIndexOf = filepath.lastIndexOf("/");  
            toFilepath = toFilepath + filepath.substring(lastIndexOf ,filepath.length());  
            File copy=new File(toFilepath);  
            //复制文件夹  
            if (!copy.exists()) {  
                copy.mkdir();  
            }  
            //遍历文件夹  
            for (File f : file.listFiles()) {  
                copy(f, copy);  
            }  
        } else {  
            if (toFile.isDirectory()) {  
                String filepath = file.getAbsolutePath();  
                filepath=filepath.replaceAll("\\\\", "/");  
                String toFilepath = toFile.getAbsolutePath();  
                toFilepath=toFilepath.replaceAll("\\\\", "/");  
                int lastIndexOf = filepath.lastIndexOf("/");  
                toFilepath = toFilepath + filepath.substring(lastIndexOf ,filepath.length());  
                  
                //写文件  
                File newFile = new File(toFilepath);  
                fis = new FileInputStream(file);  
                fos = new FileOutputStream(newFile);  
                while ((a = fis.read(b)) != -1) {  
                    fos.write(b, 0, a);  
                }  
            } else {  
                //写文件  
                fis = new FileInputStream(file);  
                fos = new FileOutputStream(toFile);  
                while ((a = fis.read(b)) != -1) {  
                    fos.write(b, 0, a);  
                }  
            }  
  
        }  
	}
	
	/**
	 * 从文件中读取序列化对象
	 * @param pathFile: 目标文件
	 * @return 序列化对象
	 */
	public static Object readFileObject(String pathFile)
	{
		FileInputStream fileInputStream = null;
		ObjectInputStream oiStream = null;
		Serializable obj = null;
		try
		{
			fileInputStream = new FileInputStream(pathFile);
			oiStream = new ObjectInputStream(fileInputStream);
			obj = (Serializable)oiStream.readObject();
		}
		catch(Exception e)
		{
			obj = null;
		}
		finally {
			try {
				if(oiStream != null)
					oiStream.close();
				if(fileInputStream != null)
					fileInputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		return obj;
	}
	
	/**
	 * 把序列化对象写入文件
	 * @param obj: 待写入的序列化对象
	 * @param filePath: 目标文件
	 */
	public static void writeFileObject(Object obj, String filePath)
	{
		FileOutputStream fileOutputStream = null;
		ObjectOutputStream objectOutputStream = null;
		try
		{
			fileOutputStream = new FileOutputStream(filePath);
			objectOutputStream = new ObjectOutputStream(fileOutputStream);
			objectOutputStream.writeObject(obj);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally {
			try {
				if(objectOutputStream != null)
					objectOutputStream.close();
				if(fileOutputStream != null)
					fileOutputStream.close();
			} catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
			
		}
	}
	
	/**
	 * 删除目录
	 * @param dir
	 * @return
	 */
	public static boolean deleteDirectory(File dir)
	{
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDirectory(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
	
	/**
	 * 把指定的文件内容读取到内存
	 * @param filePath: 文件路径
	 * @return
	 */
	public static String getFileContent(String filePath)
	{
		String encoding = "UTF-8";  
        File file = new File(filePath);  
        Long filelength = file.length();  
        byte[] filecontent = new byte[filelength.intValue()];  
        try {  
            FileInputStream in = new FileInputStream(file);  
            in.read(filecontent);  
            in.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        try {  
            return new String(filecontent, encoding);  
        } catch (UnsupportedEncodingException e) {  
            System.err.println("The OS does not support " + encoding);  
            e.printStackTrace();  
            return null;  
        }  
	}
	
	public static void writeStringFile(String filepath, String content) throws IOException
	{
		File f = new File(filepath);
		if(f.exists())
			f.delete();
//		f.createNewFile();
//		FileOutputStream fos = new FileOutputStream(f);
//		BufferWriter bw = new BufferredWrite
		Path path = Paths.get(filepath);
		try (BufferedWriter writer = Files.newBufferedWriter(path, StandardOpenOption.CREATE))
		{
			writer.write(content);
		}
	}
	
	public static String readStringFromFile(String fileName) {  
        String encoding = "UTF-8";  
        File file = new File(fileName);  
        Long filelength = file.length();  
        byte[] filecontent = new byte[filelength.intValue()];  
        try {  
            FileInputStream in = new FileInputStream(file);  
            in.read(filecontent);  
            in.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        try {  
            return new String(filecontent, encoding);  
        } catch (UnsupportedEncodingException e) {  
            System.err.println("The OS does not support " + encoding);  
            e.printStackTrace();  
            return null;  
        }  
    }  
}
